import { Component, Emit, Vue } from 'vue-property-decorator'
import organize from '../lib/request/organize'
import styles from './OrganizeTree.less'

@Component({})
export default class OrganizeTree extends Vue {
  private defaultProps: Object = {
    label: 'fullName',
    children: 'organizeList',
    isLeaf: (data: any, node: any) => {
      if (data && data.subFlag > 0) {
        return false
      }

      return true
    },
  }
  private expandedKeys: any[] = []

  protected render(h: any) {
    return (
      <div class={{ [styles.organizeTree]: true }}>
        <el-tree
          load={this.loadNode}
          {...{ props: { props: this.defaultProps } }}
          lazy
          node-key="uuid"
          expand-on-click-node={false}
          default-expanded-keys={this.expandedKeys}
          highlight-current
          on-current-change={this.handleNodeClick}
        />
      </div>
    )
  }

  async loadTreeData(data: any, resolve: any) {
    const parentUUID = data && data.uuid
    let res = await organize.getOrganizeTree(parentUUID)
    res = res.data
    if (!data) {
      this.expandedKeys.push(res.root.uuid)

      return resolve([
        {
          ...res.root,
          organizeList: res.organizeList || [],
        },
      ])
    }

    return resolve(res.organizeList)
  }

  async initTreeData(resolve: any) {
    const res = await organize.getMyManageOrganizeList()

    return resolve(res.data)
  }

  loadNode(node: any, resolve: any) {
    if (node.level === 0) {
      this.initTreeData(resolve)
    } else if (
      node.data &&
      node.data.organizeList &&
      node.data.organizeList.length > 0
    ) {
      resolve(node.data.organizeList)
    } else {
      this.loadTreeData(node.data, resolve)
    }
  }

  @Emit()
  handleNodeClick(data: any) {
    return data.uuid
  }
}
